import Global from "../Global";
import DataBase from "./DataBase";


export default class UserMgr {
    public static selfPlayerId: number = Global.playerId;

    // 单例
    private static _instance: UserMgr;
    public static get instance() {
        if (!this._instance) {
            this._instance = new UserMgr();
        }
        return this._instance;
    }

    private _userDict: Map<any, DataBase> = new Map<any, DataBase>();
    public createUser<T extends DataBase>(type: { new(saveKey): T; }, id) {
        if (this._userDict.has(id)) {
            cc.log("exist same player id:" + id);
            return;
        }
        let user = new type("UserInfo" + id);
        user.decode();
        this._userDict.set(id, user);
    }

    public createSelf<T extends DataBase>(type: { new(saveKey): T; }) {
        this.createUser(type, UserMgr.selfPlayerId);
    }

    public createOther<T extends DataBase>(type: { new(saveKey): T; }, id: number) {
        this.createUser(type, id);
    }

    public user<T extends DataBase>(id): T {
        if (this._userDict.has(id)) {
            return this._userDict.get(id) as T;
        } else {
            cc.log("not find user player id:" + id);
        }
    }

    public self<T extends DataBase>(id = UserMgr.selfPlayerId): T {
        return this.user<T>(id);
    }



    public save() {
        this._userDict.forEach((db, id) => {
            db.save();
        })
    }

}